Plotting in R with ggplot2

Graphics in R

The R language has extensive graphical capabilities.

Graphics in R may be created by many different methods including base graphics and more advanced plotting packages such as lattice.

ggplot2

The ggplot2 package was created by Hadley Wickham and provides a intuitive plotting system to rapidly generate publication quality graphics.

ggplot2 builds on the concept of the “Grammar of Graphics” (Wilkinson 2005, Bertin 1983) which describes a consistent syntax for the construction of a wide range of complex graphics by a concise description of their components.

ggplot2 is a core part of the tidyverse, a group of packages designed to make data science easy and functional in R. For an introduction to these concepts check out our tidy workshop.

Why use ggplot2

The structured syntax and high level of abstraction used by ggplot2 should allow for the user to concentrate on the vizualisations instead of creating the underlying code.

On top of this central philosophy ggplot2 has:

  • Increased flexible over many plotting systems.
  • An advanced theme system for professional/publication level graphics.
  • Large developer base – Many libraries extending its flexibility.
  • Large user base – Great documentation and active mailing list.

Getting Started With ggplot2

Getting started with ggplot2

Our dataset has a variety of variables.

##  [1] "ID"                 "Name"               "Race"               "Sex"               
##  [5] "Smokes"             "Height"             "Weight"             "Birth"             
##  [9] "State"              "Pet"                "Grade"              "Died"              
## [13] "Count"              "Date.Entered.Study" "Age"                "BMI"               
## [17] "Overweight"
## [1] 100

Our first ggplot2 graph

As seen above, in order to produce a ggplot2 graph we need a minimum of:

  • Data to be used in graph
  • Mappings of data to the graph (aesthetic mapping)
  • What type of graph we want to use (The geom to use).

Our first ggplot2 graph

In the code below we define the data as our cleaned patients data frame.

## [1] "gg"     "ggplot"
##          ID    Name  Race  Sex     Smokes Height Weight      Birth        State  Pet Grade  Died Count
## 1 AC/AH/001 Michael White Male Non-Smoker 182.87  76.57 1972-02-06      Georgia  Dog     2 FALSE  0.01
## 2 AC/AH/017   Derek White Male Non-Smoker 179.12  80.43 1972-06-15     Missouri  Dog     2 FALSE -1.31
## 3 AC/AH/020    Todd Black Male Non-Smoker 169.15  75.48 1972-07-09 Pennsylvania None     2 FALSE -0.17
## 4 AC/AH/022  Ronald White Male Non-Smoker 175.66  94.54 1972-08-17      Florida  Cat     1 FALSE -1.10
##   Date.Entered.Study Age   BMI Overweight
## 1         2015-12-01  44 22.90      FALSE
## 2         2015-12-01  43 25.07       TRUE
## 3         2015-12-01  43 26.38       TRUE
## 4         2015-12-01  43 30.64       TRUE

Now we can see that we have gg/ggplot object (pcPlot).

Our first ggplot2 graph

Within this gg/ggplot object the data has been defined.

Our first ggplot2 graph

Important information on how to map the data to the vizual properties (aesthetics) of the plot as well as what type of plot to use (geom) have however yet to specified.

## Aesthetic mapping: 
## <empty>
## list()
## list()

Our first ggplot2 graph

The information to map the data to the plot can be added now using the aes() function.

## Aesthetic mapping: 
## * `x` -> `Height`
## * `y` -> `Weight`
## list()
## list()

But we are still missing the final component of our plot, the type of plot to use (geom).

Our first ggplot2 graph

Below the geom_point function is used to specify a point plot, a scatter plot of Height values on the x-axis versus Weight values on the y values.

## Aesthetic mapping: 
## * `x` -> `Height`
## * `y` -> `Weight`
## list()
## [[1]]
## geom_point: na.rm = FALSE
## stat_identity: na.rm = FALSE
## position_identity

Our first ggplot2 graph

Our first ggplot2 graph

Now we have all the components of our plot, we need we can display the results.

Our first ggplot2 graph

More typically, the data and aesthetics are defined within ggplot function and geoms applied afterwards.

Geoms

Plot types

As we have seen, an important element of a ggplot is the geom used. Following the specification of data, the geom describes the type of plot used.

Several geoms are available in ggplot2:

  • geom_point() - Scatter plots
  • geom_line() - Line plots
  • geom_smooth() - Fitted line plots
  • geom_bar() - Bar plots
  • geom_boxplot() - Boxplots
  • geom_jitter() - Jitter to plots
  • geom_histogram() - Histogram plots
  • geom_density() - Density plots
  • geom_text() - Text to plots
  • geom_errorbar() - Errorbars to plots
  • geom_violin() - Violin plots

Histograms

## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

There are a world of geoms

An overview of geoms and thier arguments can be found at ggplot2 documentation or within the ggplot2 cheatsheet.

Aesthetics

Aesthetics

In order to change the property on an aesthetic of a plot into a constant value (e.g. set color of all points to red) we can supply the color argument to the geom_point() function.

Plot properties

As we discussed earlier however, ggplot2 makes use of aesthetic mappings to assign variables in the data to the properties/aesthetics of the plot. This allows the properties of the plot to reflect variables in the data dynamically.

In these examples we supply additional information to the aes() function to define what information to display and how it is represented in the plot.

First we can recreate the plot we saw earlier.

Color

Now we can adjust the aes mapping by supplying an argument to the color parameter in the aes function. (Note that ggplot2 accepts “color” or “color” as parameter name)

This simple adjustment allows for identification of the separation between male and female measurements for height and weight.

Aesthetics in geom

The aesthetic mappings may be set directly in the geom_points() function as previously when specifying red. This can allow the same ggplot object to be used by different aesethetic mappings and varying geoms

Aesthetics in geom

Again, for a comprehensive list of parameters and aesthetic mappings used in geom_type functions see the ggplot2 documentation for individual geoms by using ?geom_type

or visit the ggplot2 documentations pages and cheatsheet

Facets

Facets

One very useful feature of ggplot is faceting. This allows you to produce several plots that subset by variables in your data.

To facet our data into multiple plots we can use the facet_wrap or facet_grid function specifying the variable we split by.

The facet_grid function is well suited to splitting the data by two factors.

Split by 2 factors

Here we can plot the data with the Smokes variable as rows and Sex variable as columns.

facet_grid(Rows~Columns)

Split by 1 factor

To split by one factor we can apply the facet_grid() function ommiting the variable before the “~”" to facet along columns in plot.

facet_grid(~Columns)

Split by 1 factor

To split along rows in plot, the variable is placed before the “~.”.

facet_grid(Rows~.)

facet_wrap()

The facet_wrap() function offers a less grid-based structure but is well suited to faceting data by one variable.

For facet_wrap() we follow as similar syntax to facet_grid().

Multiple variables

For more complex faceting both facet_grid and facet_wrap can accept combinations of variables. Here we use facet_wrap.

Multiple variables

Or in a nice grid format using facet_grid() and the Smokes variable against a combination of Gender and Pet.

Plotting Order

Plotting order in a boxplot

We will shortly discuss how to change various aspects of the plot layout and appearance. However, a common-asked question is how to change the order in which R plots a categorical variable. Consider the boxplot to compare weights of males and females:

Plotting order and factors

Here, R decides the order to arrange the boxes according to the levels of the categorical variable. By default this is the alphabetical order. i.e. Female before Male.

##    Length     Class      Mode 
##       100 character character

Plotting order and factors

Depending on the message we want the plot to convey, we might want control over the order of boxes. The factor functions allows us to explictly change the order of the levels.

Scales

Scales

Scales and their legends have so far been handled using ggplot2 defaults. ggplot2 offers functionality to have finer control over scales and legends using the scale methods.

Scale methods are divided into functions by combinations of

  • the aesthetics they control.

  • the type of data mapped to scale.

    scale_aesthetic_type

    Try typing in scale_ then tab to autocomplete. This will provide some examples of the scale functions available in ggplot2.

Arguments

Although different scale functions accept some variety in their arguments, common arguments to scale functions include -

  • name - The axis or legend title

  • limits - Minimum and maximum of the scale

  • breaks - Label/tick positions along an axis

  • labels - Label names at each break

Controlling the X and Y scale.

Both continuous and discrete X/Y scales can be controlled in ggplot2 using:

scale_(x/y)_(continuous/discrete)

Continuous axes scales

In this example we control the continuous scale on the x-axis by providing a name, X-axis limits, the positions of breaks (ticks/labels) and the labels to place at breaks.

Controlling other scales

When using fill, color, linetype, shape, size or alpha aesthetic mappings the scales are automatically selected for you and the appropriate legends created.

In the above example the discrete colors for the Sex variable was selected by default.

Manual discrete color scale

Manual control of discrete variables can be performed using scale_aes_Of_Interest_manual with the values parameter. Additionally in this example an updated name for the legend is provided.

Colorbrewer for discrete color scale

Here we have specified the colors to be used (hence the manual) but when the number of levels to a variable are high this may be impractical and often we would like ggplot2 to choose colors from a scale of our choice.

The brewer set of scale functions allow the user to make use of a range of palettes available from colorbrewer.

  • Diverging

BrBG, PiYG, PRGn, PuOr, RdBu, RdGy, RdYlBu, RdYlGn, Spectral

  • Qualitative

Accent, Dark2, Paired, Pastel1, Pastel2, Set1, Set2, Set3

  • Sequential

Blues, BuGn, BuPu, GnBu, Greens, Greys, Oranges, OrRd, PuBu, PuBuGn, PuRd, Purples, RdPu, Reds, YlGn, YlGnBu, YlOrBr, YlOrRd

Colorbrewer palettes

For more details on palette sizes and styles visit the colorbrewer website and ggplot2 reference page.

Continuous Scales

Continuous scales

So far we have looked a qualitative scales but ggplot2 offers much functionality for continuous scales such as for size, alpha (transparancy), color and fill.

  • scale_alpha_continuous() - For Transparancy

  • scale_size_continuous() - For control of size.

alpha

Both these functions accept the range of alpha/size to be used in plotting.

Below the range of alpha to be used in plot is limited to between 0.5 and 1

Limits

The limits of the scale can also be controlled but it is important to note data outside of scale is removed from plot.

Color

Control of color/fill scales can be best achieved through the gradient subfunctions of scale.

  • scale_(color/fill)_gradient - 2 color gradient (eg. low to high BMI)

  • scale_(color/fill)_gradient2 - Diverging color scale with a midpoint color (e.g. Down, No Change, Up)

Both functions take a common set of arguments:-

  • low - color for low end of gradient scale
  • high - color for high end of gradient scale.
  • na.value - color for any NA values.

Transformations

Statistical transformations

In ggplot2 many of the statistical transformations are performed without any direct specification e.g. geom_histogram() will use stat_bin() function to generate bin counts to be used in plot.

An example of statistical methods in ggplot2 which are very useful include the stat_smooth() and stat_summary() functions.

Fitting lines

The stat_smooth() function can be used to fit a line to the data being displayed.

## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Loess and more

By default a “loess” smooth line is plotted by stat_smooth. Other methods available include lm, glm,gam,rlm.

## `geom_smooth()` using formula 'y ~ x'

Fitting lines in groups

A useful feature of ggplot2 is that it uses previously defined grouping when performing smoothing.

If color by Sex is an aesthetic mapping then two smooth lines are drawn, one for each sex.

## `geom_smooth()` using formula 'y ~ x'

Fitting lines in groups

This behaviour can be overridden by specifying an aes within the stat_smooth() function and setting inherit.aes to FALSE.

## `geom_smooth()` using formula 'y ~ x'

Summary statistics

Another useful method is stat_summary() which allows for a custom statistical function to be performed and then vizualised.

The fun parameter specifies a function to apply to the y variables for every value of x. In this example we use it to plot the quantiles of the Female and Male Height data

Themes

Themes

Themes specify the details of data independent elements of the plot. This includes titles, background color, text fonts etc.

The graphs created so far have all used the default themes, theme_grey(), but ggplot2 allows for the specification of theme used.

Predefined themes

Predefined themes can be applied to a ggplot2 object using a family of functions theme_style()

Here is a scatter with the default theme…

…and the same scatter plot with the minimal theme.

Predefined themes

Several predifined themes are available within ggplot2 including:

  • theme_bw

  • theme_classic

  • theme_dark

  • theme_gray

  • theme_light

  • theme_linedraw

  • theme_minimal

Packages such as ggthemes also contain many useful collections of predined theme_style functions.

Custom themes

As well as making use of predefined theme styles, ggplot2 allows for control over the attributes and elements within a plot through a collection of related functions and attributes.

theme() is the global function used to set attributes for the collections of elements/components making up the current plot.

Within the theme functions there are 4 general graphic elements which may be controlled…

  • rect
  • line
  • text
  • title

…and 5 groups of related elements:

  • axis
  • legend
  • strip
  • panel (plot panel)
  • plot (Global plot parameters) ]

Custom themes

These elements may be specified by the use of their appropriate element functions including:

  • element_line()
  • element_text()
  • element_rect()

and additionally element_blank() to set an element to “blank”

Custom themes

A detailed description of controlling elements within a theme can be seen at the ggplot2 vignette and by typing ?theme into the console.

Customizing your theme

To demonstrate customizing a theme, in the example below we alter one element of theme. Here we will change the text color for the plot.

  • Note because we are changing a text element we use the element_text() function.

A detailed description of which elements are available and their associated element functions can be found by typing ?theme.

Customizing your theme

Finally we may wish to remove axis line, set the background of plot panels to be white and give the strips (title above facet) a cyan background color.

Useful example for legend

A useful example of using the theme can be seen in controlling the legend. By default the legend is in right of plot.

Useful example for legend

By modifying the theme we can control the legend positioning.

+ and %+replace%

When altering themes we have been using the + operator to add themes as we would adding geoms,scales and stats.

When using the + operator

  • Themes elements specified in new scheme replace elements in old theme

  • Theme elements in the old theme which have not been specified in new theme are maintained.

This makes the + operator useful for building up from old themes.

The + operator

In the example below, we maintain all elements set by theme_bw() but overwrite the theme element attribute of the color of text.

The + operator

The consequence can be seen comparing the effect of theme() on a plot with a default theme or theme_minimal.

Since the default theme, theme_grey() contains a specification for axis.text color, I will not replace it with “+” operator.

%+replace%

In contrast %+replace% replaces all elements within a theme regardless of whether they have been previously specfied in old theme.

When using the %+replace% operator

  • Theme elements specified in new scheme replace elements in old theme

  • Theme elements in the old theme which have not been specified in new theme are also replaced by blank theme elements.

## List of 11
##  $ family       : chr ""
##  $ face         : chr "plain"
##  $ colour       : chr "black"
##  $ size         : num 11
##  $ hjust        : num 0.5
##  $ vjust        : num 0.5
##  $ angle        : num 0
##  $ lineheight   : num 0.9
##  $ margin       : 'margin' num [1:4] 0points 0points 0points 0points
##   ..- attr(*, "unit")= int 8
##  $ debug        : logi FALSE
##  $ inherit.blank: logi TRUE
##  - attr(*, "class")= chr [1:2] "element_text" "element"
## List of 11
##  $ family       : chr ""
##  $ face         : chr "plain"
##  $ colour       : chr "red"
##  $ size         : num 11
##  $ hjust        : num 0.5
##  $ vjust        : num 0.5
##  $ angle        : num 0
##  $ lineheight   : num 0.9
##  $ margin       : 'margin' num [1:4] 0points 0points 0points 0points
##   ..- attr(*, "unit")= int 8
##  $ debug        : logi FALSE
##  $ inherit.blank: logi FALSE
##  - attr(*, "class")= chr [1:2] "element_text" "element"
## List of 11
##  $ family       : NULL
##  $ face         : NULL
##  $ colour       : chr "red"
##  $ size         : NULL
##  $ hjust        : NULL
##  $ vjust        : NULL
##  $ angle        : NULL
##  $ lineheight   : NULL
##  $ margin       : NULL
##  $ debug        : NULL
##  $ inherit.blank: logi FALSE
##  - attr(*, "class")= chr [1:2] "element_text" "element"

+ and %+replace%

Original theme

+ and %+replace%

Theme modified with +

+ and %+replace%

Theme modified with %+replace%

This means that %+replace% is most useful when creating new themes.

theme_get and theme_set

In the examples we have shown you we have been modifying the theme for a specific plot. But once you have a theme that you really like you may want it to apply to every plot you draw.

The active theme is automatically applied to every plot you draw. Use theme_get to get the current theme, and theme_set to completely override it

Titles and Labels

Adding titles for plot and labels

So far no plot titles have been specified. Plot titles can be specified using the labs functions.

Adding titles for plot and labels

You can also specify titles using the ggtitle and xlab/ylab functions.

Saving Plots

Saving plots

Plots produced by ggplot can be saved in the same way as base plots

The ggsave() function allows for additional arguments to be specified including the type, resolution and size of plot.

By default ggsave() will use the size of your current graphics window when saving plots so it may be important to specify width and height arguments desired.

Contact

Any suggestions, comments, edits or questions (about content or the slides themselves) please reach out to our GitHub and raise an issue.